import 'dart:async';
import 'dart:convert';

import 'package:data_table_2/data_table_2.dart';
import 'package:flutter/material.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import '../../eventbus/EventBusUtil.dart';
import '../../eventbus/EventRefreshPart.dart';
import '../../util/BaseRequest.dart';
import '../../util/ColorUtil.dart';
import '../../util/ViewUtil.dart';
import '../dto/PriceParm.dart';
import '../dto/PricePart.dart';
import '../dto/PriceRule.dart';
import 'ParmVC.dart';


class MaterialParmVC extends StatefulWidget {
  final PricePart pricePart;
  final VoidCallback callback;
  const MaterialParmVC({super.key, required this.pricePart, required this.callback});

  @override
  State<MaterialParmVC> createState() => _MaterialParmVCState();
}

class _MaterialParmVCState extends State<MaterialParmVC> {

  StreamSubscription? streamSubscription;
  List parmList=[];
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    streamSubscription = eventBus.on<EventRefreshPart>().listen((event) {
      getDetail();
    });
    getDetail();
  }

  @override
  void dispose() {
    if (streamSubscription != null) {
      streamSubscription!.cancel();
    }
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return ShadSheet(
      constraints: const BoxConstraints(minWidth: 800,maxWidth: 800),
      title: const Text('参数编辑'),
      onClosing: (){
        widget.callback();
      },
      child: Column(
        children: [
          Row(
            children: [
              Text('参数',style: TextStyle(color:Colors.black,fontSize: ViewUtil.fontSize(22)),),
              Expanded(child: Container()),
              ViewUtil.addIcon('新增参数',(){
                PriceParm priceParm=PriceParm();
                priceParm.parentId=widget.pricePart.id;
                showShadSheet(
                  barrierColor: Colors.transparent,
                  side: ShadSheetSide.right,
                  context: context,
                  builder: (context) =>  ParmVC(
                    pricePart: widget.pricePart,
                    priceParm: priceParm,
                    callback: () {
                      //回调
                    },),
                );
              }),

            ],
          ),
          ConstrainedBox(constraints: const BoxConstraints(maxHeight: 500 ),
            child:
            DataTable2(
                isHorizontalScrollBarVisible:true,
                columnSpacing: 12,
                horizontalMargin: 12,
                columns: [
                  DataColumn2(
                    label: Text('  操作'),
                    fixedWidth: 80,
                  ),
                  DataColumn2(
                    label: Text('参数名称'),
                    size: ColumnSize.L,
                  ),
                  DataColumn2(
                    label: Text('单位'),
                    fixedWidth: 100,
                  ),
                  DataColumn2(
                    label: Text('录入方式'),
                    fixedWidth: 100,
                  ),
                  DataColumn2(
                    label: Text('是否必填'),
                    fixedWidth: 100,
                  ),
                  DataColumn2(
                    label: Text('录入数据'),
                    size: ColumnSize.L,
                  ),

                ],
                rows: getDataRows()

            ),


          )
        ],
      ),
    );
  }




  getDataRows(){
    List<DataRow> datas=[];
    for (var item in parmList) {
      datas.add(DataRow(cells: [
        DataCell(
            ViewUtil.editIcon('编辑参数',(){showShadSheet(
              side: ShadSheetSide.right,
              barrierColor: Colors.transparent,
              context: context,
              builder: (context) =>  ParmVC(
                pricePart: widget.pricePart,
                priceParm: item,
                callback: () {
                  //回调
                  getDetail();
                },),
            );}),

        ),
        DataCell(Text(item.name)),
        DataCell(Text(item.unit)),
        DataCell(Text(item.handle==0?'输入数据':'录入公式')),
        DataCell(Text(item.required==0?'非必填':"必填")),
        DataCell(Text(item.handle==0?item.value:getRuleString(item.rule))),
      ]));


    }
    return datas;
  }



  getRuleString(var rule){
    var ruleStr="";
    if(rule.isNotEmpty){
      List<dynamic> list = json.decode(rule);

      for(var item in list){
        PriceRule rule=PriceRule.fromJson(item);
        if(rule.handle==0){
          ruleStr="$ruleStr${rule.value}";
        }else{
          ruleStr="$ruleStr${rule.name}";
        }
      }
    }

    return ruleStr;
  }

  void getDetail(){
    var parm={"id":widget.pricePart.id};

    BaseRequest.postHttp("price/partdetail",parameters:parm , canTip: true, context: context, onSuccess: (data){
      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        dynamic datas=data["data"];
        PricePart pricePart= PricePart.fromJson(datas);
        widget.pricePart.parmList=pricePart.parmList;
        parmList=pricePart.parmList;
        widget.pricePart.rule=pricePart.rule;
        setState(() {

        });
      }
    }, onError: (error){

    });
  }
}
